package org.springblade.modules.admin.service.parts.impl;

import lombok.extern.slf4j.Slf4j;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.entity.MaintainPlanContent;
import org.springblade.modules.admin.enums.MaintainPlanContentEnum;
import org.springblade.modules.admin.enums.TaskStatusEnum;
import org.springblade.modules.admin.service.IMaintainPlanContentService;
import org.springblade.modules.admin.service.parts.OrderStateMachineService;
import org.springblade.modules.admin.service.parts.OrderStateStrategy;
import org.springblade.modules.admin.service.parts.PartsHandlerBeanEnum;
import org.springblade.modules.admin.service.parts.PartsStateMachine;
import org.springblade.modules.admin.vo.parts.PartsExecuteVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * @Description 配件工单状态实现
 * @Author ysq
 * @Date 2024/05/17
 **/
@Slf4j
@Service
public class OrderStateMachineServiceImpl implements OrderStateMachineService {

	@Autowired
	private Map<String, OrderStateStrategy> stateStrategyMap;

	@Autowired
	private IMaintainPlanContentService maintainPlanContentService;

	@Transactional(rollbackFor = Exception.class)
	@Override
	public Object execute(Map<String, Object> params) {
		PartsExecuteVO executeParams = Func.toBean(params, PartsExecuteVO.class);
		if (Func.isEmpty(executeParams) || Func.isEmpty(executeParams.getPlanId()) || Func.isBlank(executeParams.getEvent())) {
			throw new ServiceException("执行参数为空!");
		}
		MaintainPlanContent maintainPlanContent = maintainPlanContentService.getById(executeParams.getPlanId());
		if (Func.isEmpty(maintainPlanContent)) {
			throw new ServiceException("工单不存在!");
		}

		TaskStatusEnum curStatusEnum = TaskStatusEnum.getTaskStatusEnum(MaintainPlanContentEnum.MAINTAIN_PARTS.getId(), maintainPlanContent.getStatus());
		TaskStatusEnum targetStatusEnum = TaskStatusEnum.valueOf(executeParams.getEvent());
		// 第一步和最后一步不推进状态
		if (!Func.equalsSafe(executeParams.getEvent(), "PARTS_APPROVE") && !Func.equalsSafe(executeParams.getEvent(), "PARTS_CLOSE") ) {
			// 获取推进状态
			int targetStatus = PartsStateMachine.transferStatus(curStatusEnum, targetStatusEnum);
			executeParams.setTargetStatus(targetStatus);
		}

		// 获取对应状态的处理策略
		OrderStateStrategy orderStateStrategy = stateStrategyMap.get(PartsHandlerBeanEnum.valueOf(executeParams.getEvent()).getBeanName());
		// 执行状态处理
		return orderStateStrategy.execute(executeParams);
	}
}
